<template>
  <div class="statistics">
    <h1>数据统计图表</h1>
    <!-- 导航栏 -->
    <div class="tabs-header">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="班级统计" name="class"></el-tab-pane>
        <el-tab-pane label="学生统计" name="student"></el-tab-pane>
        <el-tab-pane label="教师统计" name="teacher"></el-tab-pane>
        <el-tab-pane label="用户统计" name="user" v-if="role === 0"></el-tab-pane>
        <el-tab-pane label="操作日志统计" name="log" v-if="role === 0"></el-tab-pane>
      </el-tabs>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <!-- 班级统计图表 -->
      <div v-show="activeTab === 'class'" class="chart-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="chart-item" ref="classChart1"></div>
          </el-col>
          <el-col :span="12">
            <div class="chart-item" ref="classChart2"></div>
          </el-col>
        </el-row>
      </div>

      <!-- 学生统计图表 -->
      <div v-show="activeTab === 'student'" class="chart-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="chart-item" ref="studentChart1"></div>
          </el-col>
          <el-col :span="12">
            <div class="chart-item" ref="studentChart2"></div>
          </el-col>
        </el-row>
      </div>

      <!-- 教师统计图表 -->
      <div v-show="activeTab === 'teacher'" class="chart-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="chart-item" ref="teacherChart1"></div>
          </el-col>
          <el-col :span="12">
            <div class="chart-item" ref="teacherChart2"></div>
          </el-col>
        </el-row>
      </div>

      <!-- 用户统计图表 -->
      <div v-show="activeTab === 'user'" class="chart-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="chart-item" ref="userChart1"></div>
          </el-col>
          <el-col :span="12">
            <div class="chart-item" ref="userChart2"></div>
          </el-col>
        </el-row>
      </div>

      <!-- 操作日志统计图表 -->
      <div v-show="activeTab === 'log'" class="chart-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="chart-item" ref="logChart1"></div>
          </el-col>
          <el-col :span="12">
            <div class="chart-item" ref="logChart2"></div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'StatisticsDemo',
  data() {
    return {
      activeTab: 'class',
      charts: {},
      classData: [],
      studentData: [],
      teacherData: [],
      userData: [],
      logData: [],
      isComponentMounted: false
    };
  },
  computed: {
    role() {
      console.log('role', this.getRole());
      return this.getRole();
    }
  },
  watch: {
    // 监听路由变化，确保组件在路由切换后重新初始化图表
    '$route': {
      handler() {
        if (this.isComponentMounted) {
          this.$nextTick(() => {
            this.destroyCharts();
            this.initCharts();
          });
        }
      },
      immediate: false
    }
  },
  methods: {
    //从LocalStorage的currentUser中获取role,可以在template中使用
    getRole() {
      const user = JSON.parse(localStorage.getItem('currentUser'));
      return user ? user.role : '';
    },
    handleTabClick() {
      // 当切换标签页时，异步加载对应的图表数据
      this.$nextTick(() => {
        this.initCharts();
      });
    },
    
    // 销毁所有图表实例
    destroyCharts() {
      Object.values(this.charts).forEach(chart => {
        if (chart) {
          try {
            chart.dispose();
          } catch (e) {
            console.error('销毁图表时出错:', e);
          }
        }
      });
      this.charts = {};
    },
    
    // 延迟初始化图表，确保DOM已完全渲染
    delayedInit() {
      setTimeout(() => {
        if (this.$refs.classChart1) {
          this.initCharts();
          this.isComponentMounted = true;
        } else {
          // 如果DOM还没准备好，再次尝试
          this.delayedInit();
        }
      }, 300); // 等待300毫秒后再次尝试
    },
    
    initCharts() {
      // 根据当前活动标签页初始化对应的图表
      switch (this.activeTab) {
        case 'class':
          this.initClassCharts();
          break;
        case 'student':
          this.initStudentCharts();
          break;
        case 'teacher':
          this.initTeacherCharts();
          break;
        case 'user':
          this.initUserCharts();
          break;
        case 'log':
          this.initLogCharts();
          break;
      }
    },
    
    // 初始化班级统计图表
    initClassCharts() {
      this.loadClassData().then(() => {
        this.$nextTick(() => {
          try {
            // 初始化班级人数分布饼图
            if (!this.charts.classChart1 && this.$refs.classChart1) {
              this.charts.classChart1 = echarts.init(this.$refs.classChart1);
            }
            
            if (this.charts.classChart1) {
              const classPieOption = {
                title: {
                  text: '班级人数分布',
                  left: 'center'
                },
                tooltip: {
                  trigger: 'item',
                  formatter: '{a} <br/>{b}: {c}人 ({d}%)'
                },
                legend: {
                  orient: 'vertical',
                  left: 'left',
                  data: this.classData.map(item => item.className)
                },
                series: [
                  {
                    name: '班级人数',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: false,
                    label: {
                      show: true,
                      formatter: '{b}: {c}人'
                    },
                    emphasis: {
                      label: {
                        show: true,
                        fontSize: '18',
                        fontWeight: 'bold'
                      }
                    },
                    data: this.classData.map(item => ({
                      name: item.className,
                      value: item.mebers
                    }))
                  }
                ]
              };
              
              this.charts.classChart1.setOption(classPieOption);
            }
            
            // 初始化班级地点统计条形图
            if (!this.charts.classChart2 && this.$refs.classChart2) {
              this.charts.classChart2 = echarts.init(this.$refs.classChart2);
            }
            
            if (this.charts.classChart2) {
              const classBarOption = {
                title: {
                  text: '班级地点分布',
                  left: 'center'
                },
                tooltip: {
                  trigger: 'axis',
                  axisPointer: {
                    type: 'shadow'
                  }
                },
                xAxis: {
                  type: 'category',
                  data: this.processLocationData(this.classData).map(item => item.location),
                  axisLabel: {
                    interval: 0,
                    rotate: 30
                  }
                },
                yAxis: {
                  type: 'value',
                  name: '班级数量'
                },
                series: [
                  {
                    name: '班级数量',
                    type: 'bar',
                    data: this.processLocationData(this.classData).map(item => item.count),
                    itemStyle: {
                      color: function(params) {
                        // 设置渐变色
                        var colorList = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de'];
                        return colorList[params.dataIndex % colorList.length];
                      }
                    }
                  }
                ]
              };
              
              this.charts.classChart2.setOption(classBarOption);
            }
          } catch (e) {
            console.error('初始化班级图表失败:', e);
          }
        });
      });
    },
    
    // 初始化学生统计图表
    initStudentCharts() {
      this.loadStudentData().then(() => {
        this.$nextTick(() => {
          try {
            // 初始化学生性别分布饼图
            if (!this.charts.studentChart1 && this.$refs.studentChart1) {
              this.charts.studentChart1 = echarts.init(this.$refs.studentChart1);
            }
            
            if (this.charts.studentChart1) {
              const genderPieOption = {
                title: {
                  text: '学生性别分布',
                  left: 'center'
                },
                tooltip: {
                  trigger: 'item',
                  formatter: '{a} <br/>{b}: {c}人 ({d}%)'
                },
                legend: {
                  orient: 'vertical',
                  left: 'left',
                  data: ['男', '女']
                },
                series: [
                  {
                    name: '性别分布',
                    type: 'pie',
                    radius: '60%',
                    center: ['50%', '50%'],
                    data: [
                      { value: this.countGender(this.studentData, 1), name: '男' },
                      { value: this.countGender(this.studentData, 0), name: '女' }
                    ],
                    emphasis: {
                      itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                      }
                    },
                    label: {
                      formatter: '{b}: {c}人 ({d}%)'
                    }
                  }
                ],
                color: ['#5470c6', '#ee6666']
              };
              
              this.charts.studentChart1.setOption(genderPieOption);
            }
            
            // 初始化学生班级分布柱状图
            if (!this.charts.studentChart2 && this.$refs.studentChart2) {
              this.charts.studentChart2 = echarts.init(this.$refs.studentChart2);
            }
            
            if (this.charts.studentChart2) {
              const classDistribution = this.getStudentClassDistribution();
              
              const studentBarOption = {
                title: {
                  text: '各班级学生人数',
                  left: 'center'
                },
                tooltip: {
                  trigger: 'axis',
                  axisPointer: {
                    type: 'shadow'
                  }
                },
                xAxis: {
                  type: 'category',
                  data: classDistribution.map(item => item.className),
                  axisLabel: {
                    interval: 0,
                    rotate: 30
                  }
                },
                yAxis: {
                  type: 'value',
                  name: '学生人数'
                },
                series: [
                  {
                    name: '学生人数',
                    type: 'bar',
                    data: classDistribution.map(item => item.count),
                    itemStyle: {
                      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#83bff6' },
                        { offset: 0.5, color: '#188df0' },
                        { offset: 1, color: '#188df0' }
                      ])
                    }
                  }
                ]
              };
              
              this.charts.studentChart2.setOption(studentBarOption);
            }
          } catch (e) {
            console.error('初始化学生图表失败:', e);
          }
        });
      });
    },
    
    // 初始化教师统计图表
    initTeacherCharts() {
      this.loadTeacherData().then(() => {
        this.$nextTick(() => {
          try {
            // 初始化教师性别分布饼图
            if (!this.charts.teacherChart1 && this.$refs.teacherChart1) {
              this.charts.teacherChart1 = echarts.init(this.$refs.teacherChart1);
            }
            
            if (this.charts.teacherChart1) {
              const genderPieOption = {
                title: {
                  text: '教师性别分布',
                  left: 'center'
                },
                tooltip: {
                  trigger: 'item',
                  formatter: '{a} <br/>{b}: {c}人 ({d}%)'
                },
                legend: {
                  orient: 'vertical',
                  left: 'left',
                  data: ['男', '女']
                },
                series: [
                  {
                    name: '性别分布',
                    type: 'pie',
                    radius: '60%',
                    center: ['50%', '50%'],
                    data: [
                      { value: this.countGender(this.teacherData, 1), name: '男' },
                      { value: this.countGender(this.teacherData, 0), name: '女' }
                    ],
                    emphasis: {
                      itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                      }
                    },
                    label: {
                      formatter: '{b}: {c}人 ({d}%)'
                    }
                  }
                ],
                color: ['#5470c6', '#ee6666']
              };
              
              this.charts.teacherChart1.setOption(genderPieOption);
            }
            
            // 初始化教师学历分布图
            if (!this.charts.teacherChart2 && this.$refs.teacherChart2) {
              this.charts.teacherChart2 = echarts.init(this.$refs.teacherChart2);
            }
            
            if (this.charts.teacherChart2) {
              const degreeData = this.getTeacherDegreeDistribution();
              
              const degreeOption = {
                title: {
                  text: '教师学历分布',
                  left: 'center'
                },
                tooltip: {
                  trigger: 'item',
                  formatter: '{a} <br/>{b}: {c}人 ({d}%)'
                },
                legend: {
                  orient: 'vertical',
                  left: 'left',
                  data: degreeData.map(item => item.degree)
                },
                series: [
                  {
                    name: '学历分布',
                    type: 'pie',
                    radius: ['30%', '60%'],
                    center: ['50%', '50%'],
                    roseType: 'radius',
                    label: {
                      formatter: '{b}: {c}人'
                    },
                    data: degreeData.map(item => ({
                      name: item.degree,
                      value: item.count
                    }))
                  }
                ]
              };
              
              this.charts.teacherChart2.setOption(degreeOption);
            }
          } catch (e) {
            console.error('初始化教师图表失败:', e);
          }
        });
      });
    },
    
    // 初始化用户统计图表
    initUserCharts() {
      this.loadUserData().then(() => {
        this.$nextTick(() => {
          try {
            // 初始化用户角色分布饼图
            if (!this.charts.userChart1 && this.$refs.userChart1) {
              this.charts.userChart1 = echarts.init(this.$refs.userChart1);
            }
            
            if (this.charts.userChart1) {
              const roleDistribution = this.getUserRoleDistribution();
              
              const rolePieOption = {
                title: {
                  text: '用户角色分布',
                  left: 'center'
                },
                tooltip: {
                  trigger: 'item',
                  formatter: '{a} <br/>{b}: {c}人 ({d}%)'
                },
                legend: {
                  orient: 'vertical',
                  left: 'left',
                  data: roleDistribution.map(item => item.name)
                },
                series: [
                  {
                    name: '角色分布',
                    type: 'pie',
                    radius: '60%',
                    center: ['50%', '50%'],
                    data: roleDistribution,
                    emphasis: {
                      itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                      }
                    },
                    label: {
                      formatter: '{b}: {c}人 ({d}%)'
                    }
                  }
                ],
                color: ['#5470c6', '#91cc75', '#fac858']
              };
              
              this.charts.userChart1.setOption(rolePieOption);
            }
            
            // 初始化用户活跃度柱状图
            if (!this.charts.userChart2 && this.$refs.userChart2) {
              this.charts.userChart2 = echarts.init(this.$refs.userChart2);
            }
            
            if (this.charts.userChart2) {
              const monthData = this.getUserRegistrationTime();
              
              const userBarOption = {
                title: {
                  text: '用户注册时间分布',
                  left: 'center'
                },
                tooltip: {
                  trigger: 'axis',
                  axisPointer: {
                    type: 'shadow'
                  }
                },
                xAxis: {
                  type: 'category',
                  data: monthData.months,
                  axisLabel: {
                    interval: 0,
                    rotate: 30
                  }
                },
                yAxis: {
                  type: 'value',
                  name: '注册人数'
                },
                series: [
                  {
                    name: '注册人数',
                    type: 'bar',
                    data: monthData.counts,
                    itemStyle: {
                      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#83bff6' },
                        { offset: 0.5, color: '#188df0' },
                        { offset: 1, color: '#188df0' }
                      ])
                    }
                  }
                ]
              };
              
              this.charts.userChart2.setOption(userBarOption);
            }
          } catch (e) {
            console.error('初始化用户图表失败:', e);
          }
        });
      });
    },
    
    // 初始化操作日志统计图表
    initLogCharts() {
      this.loadLogData().then(() => {
        this.$nextTick(() => {
          try {
            // 初始化操作类型分布饼图
            if (!this.charts.logChart1 && this.$refs.logChart1) {
              this.charts.logChart1 = echarts.init(this.$refs.logChart1);
            }
            
            if (this.charts.logChart1) {
              const operateTypeOption = {
                title: {
                  text: '操作类型分布',
                  left: 'center'
                },
                tooltip: {
                  trigger: 'item',
                  formatter: '{a} <br/>{b}: {c}次 ({d}%)'
                },
                legend: {
                  orient: 'vertical',
                  left: 'left',
                  data: ['新增', '修改', '删除']
                },
                series: [
                  {
                    name: '操作类型',
                    type: 'pie',
                    radius: '60%',
                    center: ['50%', '50%'],
                    data: [
                      { value: this.countOperateType(this.logData, 1), name: '新增' },
                      { value: this.countOperateType(this.logData, 2), name: '修改' },
                      { value: this.countOperateType(this.logData, 3), name: '删除' }
                    ],
                    emphasis: {
                      itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                      }
                    },
                    label: {
                      formatter: '{b}: {c}次 ({d}%)'
                    }
                  }
                ],
                color: ['#91cc75', '#fac858', '#ee6666']
              };
            
              this.charts.logChart1.setOption(operateTypeOption);
            }
            
            // 初始化目标类型分布图
            if (!this.charts.logChart2 && this.$refs.logChart2) {
              this.charts.logChart2 = echarts.init(this.$refs.logChart2);
            }
            
            if (this.charts.logChart2) {
              // 按操作时间统计
              const timeData = this.getLogTimeDistribution();
              
              const timeOption = {
                title: {
                  text: '操作时间分布',
                  left: 'center'
                },
                tooltip: {
                  trigger: 'axis',
                  axisPointer: {
                    type: 'line'
                  }
                },
                legend: {
                  data: ['学生', '教师', '管理员'], // 添加管理员统计
                  bottom: 0
                },
                xAxis: {
                  type: 'category',
                  data: timeData.dates,
                  axisLabel: {
                    interval: 0,
                    rotate: 40
                  }
                },
                yAxis: {
                  type: 'value',
                  name: '操作次数'
                },
                series: [
                  {
                    name: '学生',
                    type: 'line',
                    data: timeData.student,
                    smooth: true
                  },
                  {
                    name: '教师',
                    type: 'line',
                    data: timeData.teacher,
                    smooth: true
                  },
                  {
                    name: '管理员',
                    type: 'line',
                    data: timeData.admin, // 添加管理员数据
                    smooth: true
                  }
                ]
              };
              
              this.charts.logChart2.setOption(timeOption);
            }
          } catch (e) {
            console.error('初始化日志图表失败:', e);
          }
        });
      });
    },

    // 统计操作类型数量
    countOperateType(data, type) {
      return data.filter(item => item.operateType === type).length;
    },

    // 新增方法用于统计用户操作类型数量
    countUserOperateType(data) {
      return data.filter(item => item.targetType === 3).length;
    },

    // 修改 getLogTimeDistribution 方法以包含管理员数据
    getLogTimeDistribution() {
      // 按天统计最近7天的操作
      const result = {
        dates: [],
        student: [],
        teacher: [],
        admin: [] // 添加管理员数据
      };

      // 获取最近7天的日期
      const dates = [];
      for (let i = 6; i >= 0; i--) {
        const date = new Date();
        date.setDate(date.getDate() - i);
        dates.push(this.formatDate(date));
      }

      result.dates = dates;

      // 初始化每天的操作次数
      for (let i = 0; i < 7; i++) {
        result.student[i] = 0;
        result.teacher[i] = 0;
        result.admin[i] = 0;
      }

      // 统计每天的操作次数
      this.logData.forEach(log => {
        if (!log.createTime) return;

        const dateStr = log.createTime.substring(0, 10);
        const index = dates.indexOf(dateStr);

        if (index !== -1) {
          if (log.targetType === 1) { // 学生
            result.student[index]++;
          } else if (log.targetType === 2) { // 教师
            result.teacher[index]++;
          } else if (log.targetType === 0) { // 管理员
            result.admin[index]++;
          }
        }
      });

      return result;
    },
    
    // 加载班级数据
    loadClassData() {
      return this.$http.get(this.httpUrl + '/class/list')
        .then(res => {
          if (res.data && res.data.code === 200) {
            this.classData = res.data.data || [];
          } else {
            this.$message.error('获取班级数据失败');
            this.classData = [];
          }
        })
        .catch(err => {
          console.error('班级数据加载失败:', err);
          this.$message.error('班级数据加载失败，请检查网络');
          this.classData = [];
        });
    },
    
    // 加载学生数据
    loadStudentData() {
      return this.$http.post(this.httpUrl + '/student/listPage', {
        pageSize: 1000,  // 设置较大的值以获取所有数据
        pageNum: 1,
        param: {}
      })
      .then(res => {
        if (res.data && res.data.code === 200) {
          this.studentData = res.data.data || [];
        } else {
          this.$message.error('获取学生数据失败');
          this.studentData = [];
        }
      })
      .catch(err => {
        console.error('学生数据加载失败:', err);
        this.$message.error('学生数据加载失败，请检查网络');
        this.studentData = [];
      });
    },
    
    // 加载教师数据
    loadTeacherData() {
      return this.$http.post(this.httpUrl + '/teacher/listPage', {
        pageSize: 1000,  // 设置较大的值以获取所有数据
        pageNum: 1,
        param: {}
      })
      .then(res => {
        if (res.data && res.data.code === 200) {
          this.teacherData = res.data.data || [];
        } else {
          this.$message.error('获取教师数据失败');
          this.teacherData = [];
        }
      })
      .catch(err => {
        console.error('教师数据加载失败:', err);
        this.$message.error('教师数据加载失败，请检查网络');
        this.teacherData = [];
      });
    },
    
    // 加载用户数据
    loadUserData() {
      return this.$http.post(this.httpUrl + '/user/listPage', {
        pageSize: 1000,  // 设置较大的值以获取所有数据
        pageNum: 1,
        param: {}
      })
      .then(res => {
        if (res.data && res.data.code === 200) {
          this.userData = res.data.data || [];
        } else {
          this.$message.error('获取用户数据失败');
          this.userData = [];
        }
      })
      .catch(err => {
        console.error('用户数据加载失败:', err);
        this.$message.error('用户数据加载失败，请检查网络');
        this.userData = [];
      });
    },
    
    // 加载日志数据
    loadLogData() {
      return this.$http.post(this.httpUrl + '/log/listPage', {
        pageSize: 1000,  // 设置较大的值以获取所有数据
        pageNum: 1,
        param: {}
      })
      .then(res => {
        if (res.data && res.data.code === 200) {
          this.logData = res.data.data || [];
        } else {
          this.$message.error('获取日志数据失败');
          this.logData = [];
        }
      })
      .catch(err => {
        console.error('日志数据加载失败:', err);
        this.$message.error('日志数据加载失败，请检查网络');
        this.logData = [];
      });
    },
    
    // 处理班级地点数据
    processLocationData(data) {
      // 统计每个地点的班级数量
      const locationMap = {};
      
      data.forEach(item => {
        if (item.location) {
          locationMap[item.location] = (locationMap[item.location] || 0) + 1;
        }
      });
      
      // 转换为数组
      return Object.keys(locationMap).map(location => ({
        location: location,
        count: locationMap[location]
      }));
    },
    
    // 统计性别数量
    countGender(data, gender) {
      let count = 0;
      data.forEach(item => {
        // 学生和教师性别字段可能不同
        if ((item.sex !== undefined && item.sex === gender) || 
            (item.tSex !== undefined && item.tSex === gender)) {
          count++;
        }
      });
      return count;
    },
    
    // 获取学生班级分布
    getStudentClassDistribution() {
      const classMap = {};
      
      this.studentData.forEach(student => {
        if (student.className) {
          classMap[student.className] = (classMap[student.className] || 0) + 1;
        }
      });
      
      // 转换为数组
      return Object.keys(classMap).map(className => ({
        className: className,
        count: classMap[className]
      }));
    },
    
    // 获取用户角色分布
    getUserRoleDistribution() {
      const roleMap = {
        0: '管理员',
        1: '教师',
        2: '学生'
      };
      
      const distribution = {};
      
      this.userData.forEach(user => {
        const roleName = roleMap[user.role] || '未知角色';
        distribution[roleName] = (distribution[roleName] || 0) + 1;
      });
      
      // 转换为数组
      return Object.keys(distribution).map(roleName => ({
        name: roleName,
        value: distribution[roleName]
      }));
    },
    
    // 获取用户注册时间分布
    getUserRegistrationTime() {
      const result = {
        months: [],
        counts: []
      };
      
      // 获取最近6个月
      const monthData = {};
      for (let i = 5; i >= 0; i--) {
        const date = new Date();
        date.setMonth(date.getMonth() - i);
        const month = date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0');
        monthData[month] = 0;
      }
      
      // 统计每月注册用户数
      this.userData.forEach(user => {
        if (user.createTime) {
          const date = new Date(user.createTime);
          const month = date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0');
          
          if (monthData[month] !== undefined) {
            monthData[month]++;
          }
        }
      });
      
      // 转换为数组
      result.months = Object.keys(monthData);
      result.counts = Object.values(monthData);
      
      return result;
    },
    
    // 获取教师学历分布
    getTeacherDegreeDistribution() {
      const degreeMap = {};
      
      this.teacherData.forEach(teacher => {
        if (teacher.degree) {
          degreeMap[teacher.degree] = (degreeMap[teacher.degree] || 0) + 1;
        }
      });
      
      // 转换为数组
      return Object.keys(degreeMap).map(degree => ({
        degree: degree,
        count: degreeMap[degree]
      }));
    },
    
    // 格式化日期为 yyyy-MM-dd
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    // 窗口调整大小时，重新绘制图表
    resizeCharts() {
      Object.values(this.charts).forEach(chart => {
        if (chart) {
          chart.resize();
        }
      });
    }
  },
  mounted() {
    console.log('StatisticsDemo mounted');
    // 使用 $nextTick 确保 DOM 已经渲染
    this.$nextTick(() => {
      // 使用延迟初始化来确保DOM元素已经完全渲染
      this.delayedInit();
      
      // 监听窗口调整大小事件
      window.addEventListener('resize', this.resizeCharts);
    });
  },
  updated() {
    console.log('StatisticsDemo updated');
    // 组件更新时，确保图表正确展示
    this.$nextTick(() => {
      this.resizeCharts();
    });
  },
  beforeDestroy() {
    console.log('StatisticsDemo beforeDestroy');
    // 移除事件监听
    window.removeEventListener('resize', this.resizeCharts);
    
    // 销毁图表实例
    this.destroyCharts();
  }
};
</script>

<style scoped>
.statistics {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
}

.tabs-header {
  margin-bottom: 20px;
}

.charts-container {
  flex: 1;
  width: 100%;
  position: relative;
}

.chart-section {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

.chart-item {
  height: 450px;
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

h1 {
  margin-bottom: 20px;
}

/* 确保表格不会超出容器 */
.el-table {
  width: 100%;
}
</style> 